//
//  TMMacroCatalogController.m
//  Textmaster
//
//  Created by Anshu Chimala on 1/2/10.
//  Copyright 2010 Home. All rights reserved.
//

#import "TMMacroCatalogController.h"
#import "TMWindow.h"
#import "JSON.h"
#import "TextmasterAppDelegate.h"
#import "SourceListTextCell.h"

@implementation TMMacroCatalogController

- (void)awakeFromNib {
	// A queue so that one day, in the future, we can have
	// multiple downloads going at the same time?
	// Nah that would require NSURLDownloads or something
	_catalog = nil;
	_queue = [[NSOperationQueue alloc] init];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reset:) name:@"resetCatalog" object:nil];
}

- (void)dealloc {
	[_queue release], _queue = nil;
	[_catalog release], _catalog = nil;
	[super dealloc];
}

- (void)windowDidBecomeKey:(NSNotification *)notification {
	if(_catalog)
		return;
	
	[_progressWheel setIndeterminate:YES];
	[_progressWheel startAnimation:nil];
	[_progressText setStringValue:@"Loading Catalog..."];
	
	
	[NSApp beginSheet:_progressScreen modalForWindow:_catalogScreen modalDelegate:nil didEndSelector:nil contextInfo:nil];
	
	// Heh, this is code from an iPhone app I'm working on
	// Nice how it adapts flawlessly to this
	HTTPOperation *hop = [[HTTPOperation alloc] init];
	[hop setDelegate:self];
	[hop setTargetURL:[NSURL URLWithString:@"http://textmaster.googlecode.com/svn/web/macro-catalog"]];
	[hop setSuccessSelector:@selector(gotMacroCatalog:)];
	[hop setFailureSelector:@selector(failedToGetMacroCatalog:)];
	[_queue addOperation:hop];
	[hop release];
}

- (void)gotMacroCatalog:(NSData *)data {
	@try {
		NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
		_catalog = [[str JSONValue] retain];
		[str release];
		
		[_tableView reloadData];
		
		[NSApp endSheet:_progressScreen];
		[_progressScreen orderOut:nil];
	}
	@catch (NSException *ex) {
		NSAlert *alert = [NSAlert alertWithMessageText:@"Error" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:[ex reason]];
		[alert setAlertStyle:NSCriticalAlertStyle];
		[alert runModal];
	}
}

- (void)failedToGetMacroCatalog:(NSError *)error {
	_catalog = [[NSArray array] retain]; // Prevent it from trying to make another HTTP request
	
	[NSApp endSheet:_progressScreen];
	[_progressScreen orderOut:nil];
	
	NSAlert *alert = [NSAlert alertWithMessageText:@"Error" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:[error localizedDescription]];
	[alert setAlertStyle:NSCriticalAlertStyle];
	[alert runModal];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return [_catalog count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
	// This works because I've set up the xib with the right identifiers
	// which happen to be "title," "author," and "description"
	
    return [[_catalog objectAtIndex:row] objectForKey:[tableColumn identifier]];
}

- (void)install:(id)sender {
	[_progressText setStringValue:@"Downloading..."];
	[NSApp beginSheet:_progressScreen modalForWindow:_catalogScreen modalDelegate:nil didEndSelector:nil contextInfo:nil];
	
	int row = [_tableView selectedRow];
	if(row<0)
		return;
	
	NSString *url = [[_catalog objectAtIndex:row] valueForKey:@"url"];
	_download = [[NSURLDownload alloc] initWithRequest:[NSURLRequest requestWithURL:
														[NSURL URLWithString:url]]
											  delegate:self];
	[_download setDestination:[@"~/Library/Application Support/Textmaster/PlugIns/tmp.zip" stringByExpandingTildeInPath]
			   allowOverwrite:YES];
}

- (void)reset:(id)sender {
	if(_catalog)
		[_catalog release];
	_catalog = nil;
}

- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response {
    // reset the progress, this might be called multiple times
    _bytesReceived=0;
	
	if(_response)
		[_response release];
	_response = [response retain];
}

- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(NSUInteger)length {
    long long expectedLength=[_response expectedContentLength];
	
    _bytesReceived+=length;
	
    if (expectedLength != NSURLResponseUnknownLength) {
        float percentComplete=(_bytesReceived/(float)expectedLength)*100.0;
		[_progressWheel setIndeterminate:NO];
		[_progressWheel setDoubleValue:percentComplete];
    }
	else {
		[_progressWheel setIndeterminate:YES];
		[_progressWheel startAnimation:nil];
    }
}

- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error {
	[NSApp endSheet:_progressScreen];
	[_progressScreen orderOut:nil];
	
	NSAlert *alert = [NSAlert alertWithMessageText:@"Error" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:[error localizedDescription]];
	[alert setAlertStyle:NSCriticalAlertStyle];
	[alert beginSheetModalForWindow:_catalogScreen modalDelegate:nil didEndSelector:nil contextInfo:nil];
}

- (void)downloadDidFinish:(NSURLDownload *)download {
	[NSApp endSheet:_progressScreen];
	[_progressScreen orderOut:nil];
	[_download release], _download = nil;
	
	system("cd ~/Library/Application\\ Support/Textmaster/PlugIns && unzip tmp.zip && rm -rf tmp.zip _MACOSX");
	
	[NSApp endSheet:_progressScreen];
	[_progressScreen orderOut:nil];
}

@end
